//
//  HomeViewController.m
//  FastDoctor
//
//  Created by 王炯 on 16/7/6.
//  Copyright © 2016年 sc. All rights reserved.
//
#import "HomeViewController.h"
#import "WeatherView.h"
#import "CityViewController.h"
#import <UIImageView+WebCache.h>

#import "BannerCell.h"
#import "ReloadWeatherData.h"

#import "BottomView.h"

#import "DiseaseMedicalViewController.h"
#import "PublicAdvertViewController.h"
#import "SignViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CLLocationManagerDelegate>

@property(nonatomic,strong)NSArray *array;
@property(nonatomic,weak)UICollectionView *collectionView;
@property(nonatomic,weak)UIPageControl *pageController;

@property(nonatomic,weak)NSTimer *timer;


 //定义属性用于传递数据 勿删!!!
@property (nonatomic,weak) WeatherView *weatherView;
@property(nonatomic,weak)BottomView *bottomView;

//定位
@property (nonatomic,strong)CLLocationManager *locationManager;

//获取当前位置
@property (nonatomic,strong) CLLocation *currentLocation;

//获取当前城市
@property (nonatomic,copy)NSString *locationCity;




@end

@implementation HomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化GPS定位系统
    [self SetUpGPSLocation];
    
    [self setupHomeViewContent];
    [self setupBottomView];
    
    //禁用掉系统自动的布局效果
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //添加监听通知获取网络数据  勿删!!!!!
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(turnToCityViewController) name:@"city" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNetworkData:) name:@"network" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(turnToDiseaseMedicalViewController:) name:@"disease" object:nil];
}

-(void)SetUpGPSLocation
{
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    
    self.locationManager = locationManager;
    
    locationManager.delegate = self;
    
    //设置定位精度
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    //设备移动多少米之后才能将一个更新发给委托
    locationManager.distanceFilter = 20;
    
    //发出授权申请，允许使用定位服务
    [locationManager requestAlwaysAuthorization];
    
    //更新位置
    [locationManager startUpdatingLocation];
    
    //更新方向
    [locationManager startUpdatingHeading];
}

//1-通过以下方法，可以获得设备是否允许使用定位服务
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusNotDetermined || status == kCLAuthorizationStatusDenied)
    {
        //允许使用定位服务
        //更新位置
        [self.locationManager startUpdatingLocation];
        
        //更新方向
        [self.locationManager startUpdatingHeading];
        
    }
    /*
    else
    {
        //提示打开GPS
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"GPS没打开们，请打开定位" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        
    }
    */
}
//2-定位改变时委托会执行这个方法(会一直调用此代理方法)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //获取最新的坐标
    self.currentLocation = locations.lastObject;
    
    [self LocateCity];
}
//3-地理位置信息反编码
-(void)LocateCity
{
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    
    //地点位置标示
    __block CLPlacemark *p;
    
    
    [geoCoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        //强制成中文
        NSArray *array = @[@"zh-hans"];
        
        //偏好存储
        [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"AppleLanguages"];
        
        //显示所有信息
        if (error != nil)
        {
            self.locationCity = @"数据为空";
            
            
            //重新定位地点
            [self initDataWithStringWithCity:self.locationCity];
            
            
            return ;
        }
        if (placemarks.count > 0)
        {
            p = placemarks[0];
            
            self.locationCity = p.locality;
            //重新定位地点
            [self initDataWithStringWithCity:self.locationCity];
        }
        else
        {
            self.locationCity = @"数据没有地点信息";
            
            
            //重新定位地点
            [self initDataWithStringWithCity:self.locationCity];
            
        }
    }];
    
}


- (void)setupHomeViewContent
{
    
    self.view.backgroundColor = WHITE_COLOR;
    self.navigationController.navigationBar.barTintColor = kThemeColor;
    
    self.title = @"第12组";

     //设置天气状态栏
    [self setupWeatherView];
    [self initDataWithStringWithCity:@"北京"];
    
     //设置图片轮播器
    [self setupCollectionView];
    [self setupPageController];

}
//***********************************名医通部分******************************

-(void)setupBottomView{
    BottomView *bView = [[BottomView alloc]init];
    self.bottomView = bView;
    
    [self.view addSubview:bView];
}

  //点击名医通相关按钮实现的逻辑功能
- (void)turnToDiseaseMedicalViewController:(NSNotification *)notification {
    
    NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath(@"user.data")];
    
    if (!dict) {
        [self notice];
        return;
    }

    UIButton *button = notification.userInfo[@"button"];
    
    if (button.tag == 5) {
        
        PublicAdvertViewController *publicVC = [[PublicAdvertViewController alloc]init];
        
        publicVC.title =@"公益";
        
        [self.navigationController pushViewController:publicVC animated:YES];
        return;
    }
    
    DiseaseMedicalViewController *diseaseVC = [[DiseaseMedicalViewController alloc]init];
    switch (button.tag) {
        case 0:
            
            diseaseVC.title = @"肿瘤";
            break;
        case 1:
            
            diseaseVC.title = @"心血管";
            break;
        case 2:
            
            diseaseVC.title = @"神经科";
            break;
        case 3:
            
            diseaseVC.title = @"血液科";
            break;
        case 4:
            
            diseaseVC.title = @"骨科";
            break;
        default:
            break;
    }
    [self.navigationController pushViewController:diseaseVC animated:YES];
    
}

- (void)notice {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您还没有登录,请登陆后再试" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        SignViewController *signVC = [[SignViewController alloc]init];
        
        [self.navigationController pushViewController:signVC animated:YES];
    }];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:nil];
}
//***********************************名医通部分**********************************************

//*************************************天气状态栏部分******************************************
//加载天气状态栏
- (void)setupWeatherView {
    
    WeatherView *weatherView = [[WeatherView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, (SCREEN_HEIGHT == 568 ? 80 : 100))];
    
    self.weatherView = weatherView;
    
    [self.view addSubview:weatherView];
}

//点击城市切换控制器
- (void)turnToCityViewController {
    
    CityViewController *cityViewController = [[CityViewController alloc]init];
    
    cityViewController.title = @"选择当前省份位置";
    
    [self.navigationController pushViewController:cityViewController animated:YES];
}

//获取到网络数据
- (void)getNetworkData:(NSNotification *)notification {
    
    self.view.userInteractionEnabled = YES;
    [self.collectionView reloadData];
    
    NSDictionary *dict = notification.userInfo;
    NSDictionary *weatherDict = dict[@"weather"];
    NSString *str = dict[@"city"];
    
    self.weatherView.weatherDict = weatherDict;
    self.weatherView.cityStr = str;
}

 //初始化天气数据
- (void)initDataWithStringWithCity:(NSString *)cityStr {
    
    
    [SVProgressHUD show];
    
    self.view.userInteractionEnabled = NO;
    
    
    [ReloadWeatherData initNetworkDataWithString:cityStr];
    
}


//*************************************天气状态栏部分******************************************



//***********************************图片轮播实现**********************************************
-(void)setupCollectionView{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    
    
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width,200);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing =0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    
    
    CGRect collectionRect;
    
    if (kDevice_Is_iPhone5)
    {
        collectionRect = CGRectMake(0, 144, self.view.bounds.size.width, 200);
    }
    else
    {
        collectionRect = CGRectMake(0, 164, self.view.bounds.size.width, 200);
    }
    
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:collectionRect collectionViewLayout:flowLayout];
    
    
    collectionView.delegate = self;
    collectionView.dataSource =self;
    self.collectionView = collectionView;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    
    [self.view addSubview:collectionView];
    [collectionView registerClass:[BannerCell class] forCellWithReuseIdentifier:@"bannerCell"];
    
    
}

-(void)setupPageController{
    
    UIPageControl *pageController = [[UIPageControl alloc]init];
    self.pageController = pageController;
    
    
    
    self.pageController.numberOfPages = self.array.count;
    
    self.pageController.currentPage = 0;
    
    self.pageController.pageIndicatorTintColor = [UIColor grayColor];
    
    
    self.pageController.currentPageIndicatorTintColor = [UIColor whiteColor];
    [self.view addSubview:pageController];
    
    [self.pageController mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(200);
        
        if (kDevice_Is_iPhone5)
        {
            make.top.offset(314);
        }
        else
        {
            make.top.offset(324);
        }
    }];
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return  3;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.array.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BannerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bannerCell" forIndexPath:indexPath];
    
    cell.imgsrc = self.array[indexPath.item % self.array.count];
    
    return cell;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int index = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;
    index = index % self.array.count;
    
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:1] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    
    NSInteger page =(scrollView.contentOffset.x / self.view.frame.size.width ) ;
    NSInteger current = page %3;
    
    self.pageController.currentPage =current;
    
    
}
//结束拖拽时调用(手动拖拽的时候调用)
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self setupTimer];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    
//    CGFloat offsetX = scrollView.contentOffset.x;
  
    
    if (scrollView.contentOffset.x >= (self.view.frame.size.width * (3 + 1)))
    {
        [self.collectionView setContentOffset:CGPointMake(self.view.frame.size.width, 0)];
        
    }
    else if (scrollView.contentOffset.x <= 0)
    {
        [self.collectionView setContentOffset:CGPointMake(self.view.frame.size.width * 3, 0)];
    }
    NSInteger page =(scrollView.contentOffset.x / self.view.frame.size.width ) ;
    NSInteger current = page %3;
    
    self.pageController.currentPage =current;
    
}

//当开始拖拽时调用(手动拖拽的时候调用)
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.timer invalidate];
}
- (void)setupTimer{
    __weak typeof(self) weakSelf = self;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(nextPage) userInfo:nil repeats:YES];
    
}
- (void)nextPage
{
    //获取当前PageController的点
    NSInteger currentPage = _pageController.currentPage;
    
    
    
    //点加一
    currentPage++;
    
    //赋值回去
    _pageController.currentPage = currentPage;
    
    
    
    //设置滚动条偏移动画效果
    //滚动条的x轴偏移量为currentPage*(_scrollView.frame.size.width)
    
   
         [self.collectionView setContentOffset:CGPointMake((currentPage)*(self.view.bounds.size.width), 0) animated:YES];
    
    
    
    
    
    /*
    CGFloat offsetX = self.collectionView.contentOffset.x + self.view.bounds.size.width;
    NSLog(@"%f",offsetX);
    
    NSUInteger count = offsetX/self.view.bounds.size.width;
    NSLog(@"%lu",(unsigned long)count);
    
    [self.collectionView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    */
}

-(NSArray*)array{
    
    if (_array ==nil) {
        
        _array = @[@"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                   @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                   @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                   ];
        
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    return _array;
}
//***********************************图片轮播实现**********************************************


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setupTimer];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.timer invalidate];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];

    self.bottomView.frame = CGRectMake(0, self.collectionView.frame.origin.y +self.collectionView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height- self.collectionView.frame.origin.y -self.collectionView.frame.size.height);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    //控制器销毁时移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}


@end
